<!--
 * @Author: mayijun
 * @Date: 2022-06-17 10:23:05
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-09 11:11:02
-->
<script lang="ts" setup>
import dayjs from 'dayjs';
import { reactive, ref, watch } from 'vue';
import DateSelect from './dateSelect.vue';

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  tagData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['dateDialogClose', 'dateDialogConfirm']);

let ruleFormRef = ref();

const validateStartDate = (value: any, callback: any) => {
  if (value == undefined) {
    callback('请选择开始日期');
  } else {
    if (state.ruleForm.endDate != '') {
      ruleFormRef.value.validateField('endDate');
    }
  }
  callback();
};

const validateEndDate = (value: any, callback: any) => {
  if (value == undefined) {
    callback('请选择结束日期');
  } else {
    if (state.ruleForm.startDate != '') {
      let num = Number(value);
      if (num == 0) {
        if (Date.parse(state.ruleForm.startDate) > Date.parse(value)) {
          callback('结束时间必须大于开始时间');
        }
      } else {
        if (state.ruleForm.startDate > value) {
          callback('结束时间必须大于开始时间');
        }
      }
    }
  }
  callback();
};
const state = reactive({
  ruleForm: {
    startDate: '',
    endDate: '',
    rangeType: props.tagData.rangeType
  },
  rules: {
    startDate: [
      {
        validator: validateStartDate
      }
    ],
    endDate: [
      {
        validator: validateEndDate
      }
    ]
  }
});

const handleClose = () => {
  emit('dateDialogClose', false);
  state.ruleForm.startDate = '';
  state.ruleForm.endDate = '';
};

const handleConfirm = () => {
  ruleFormRef.value.validate((valid: any) => {
    if (!valid) {
      let dateValue = state.ruleForm.startDate + ',' + state.ruleForm.endDate;
      //周日期格式处理
      if (state.ruleForm.rangeType == 'FIXED' && props.tagData.id == -5) {
        let start = getYearWeek(new Date(state.ruleForm.startDate));
        let end = getYearWeek(new Date(state.ruleForm.endDate));
        dateValue = start + ',' + end;
      }
      emit('dateDialogConfirm', dateValue, state.ruleForm.rangeType);
      handleClose();
    }
  });
  return false;
};

//切换日期类型
const rangeTypeChange = () => {
  if (state.ruleForm.rangeType == 'RELATIVE') {
    state.ruleForm.startDate = '-1';
    state.ruleForm.endDate = '-1';
  } else {
    state.ruleForm.startDate = '';
    state.ruleForm.endDate = '';
  }
  ruleFormRef.value.clearValidate();
};

//获取周的日期格式
const getYearWeek = (date: any) => {
  let y = new Date().getFullYear(); //获取年份
  let startDate = new Date(y, 0, 1);
  let d = Math.round((date.valueOf() - startDate.valueOf()) / 86400000);
  return y + '-' + Math.ceil((d + (startDate.getDay() + 1 - 1)) / 7);
};

//根据周的日期格式获取日期格式
const getDateOfWeek = (w: any, y: any) => {
  var simple = new Date(y, 0, 1 + (w - 1) * 7);
  var dow = simple.getDay();
  var weekStart = simple;
  if (dow <= 4) {
    weekStart.setDate(simple.getDate() - simple.getDay() + 1);
  } else {
    weekStart.setDate(simple.getDate() + 8 - simple.getDay());
  }
  return dayjs(weekStart).format('YYYY-MM-DD');
};

//日期快捷
const getFastDate = (type: number) => {
  switch (type) {
    case 1:
      //昨天
      state.ruleForm.startDate = dayjs()
        .add(-1, 'day')
        .startOf('day')
        .format('YYYY-MM-DD');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 2:
      //今天
      state.ruleForm.startDate = dayjs().startOf('day').format('YYYY-MM-DD');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 3:
      //近3天
      state.ruleForm.startDate = dayjs()
        .add(-2, 'day')
        .startOf('day')
        .format('YYYY-MM-DD');
      state.ruleForm.endDate = dayjs().startOf('day').format('YYYY-MM-DD');
      return false;
    case 4:
      //近七天
      state.ruleForm.startDate = dayjs()
        .add(-6, 'day')
        .startOf('day')
        .format('YYYY-MM-DD');
      state.ruleForm.endDate = dayjs().startOf('day').format('YYYY-MM-DD');
      return false;
    case 5:
      //上周
      state.ruleForm.startDate = dayjs()
        .add(-1, 'week')
        .startOf('week')
        .format('YYYY-MM-DD');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 6:
      //本周
      state.ruleForm.startDate = dayjs().startOf('week').format('YYYY-MM-DD');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 7:
      //上月
      state.ruleForm.startDate = dayjs()
        .add(-1, 'month')
        .startOf('month')
        .format('YYYY-MM');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 8:
      //本月
      state.ruleForm.startDate = dayjs().startOf('month').format('YYYY-MM');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 9:
      //近3月
      state.ruleForm.startDate = dayjs()
        .add(-2, 'month')
        .startOf('month')
        .format('YYYY-MM');
      state.ruleForm.endDate = dayjs().startOf('month').format('YYYY-MM');
      return false;
    case 10:
      //去年
      state.ruleForm.startDate = dayjs()
        .add(-1, 'year')
        .startOf('year')
        .format('YYYY');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 11:
      //今年
      state.ruleForm.startDate = dayjs().startOf('year').format('YYYY');
      state.ruleForm.endDate = state.ruleForm.startDate;
      return false;
    case 12:
      //近3年
      state.ruleForm.startDate = dayjs()
        .add(-2, 'year')
        .startOf('year')
        .format('YYYY');
      state.ruleForm.endDate = dayjs().startOf('year').format('YYYY');
      return false;
    default:
      return false;
  }
};

watch(
  () => props.dialogVisible,
  (val: any) => {
    if (val) {
      if (props.tagData) {
        let dateValue = [];
        if (Array.isArray(props.tagData.value)) {
          dateValue = props.tagData.value;
        } else {
          dateValue = props.tagData.value.split(',');
        }
        //周日期格式处理
        if (props.tagData.rangeType == 'FIXED' && props.tagData.id == -5) {
          let start = dateValue[0].split("-");
          state.ruleForm.startDate = getDateOfWeek(start[1],start[0]);
          let end = dateValue[0].split("-");
          state.ruleForm.endDate = getDateOfWeek(end[1],end[0]);
        } else {
          state.ruleForm.startDate = dateValue[0];
          state.ruleForm.endDate = dateValue[1];
        }

        state.ruleForm.rangeType = props.tagData.rangeType || 'FIXED';
      }
    }
  },
  { immediate: true }
);
</script>
<template>
  <a-modal
    title="时间选择"
    v-model:visible="props.dialogVisible"
    @before-ok="handleConfirm"
    @cancel="handleClose"
    modal-class="a-model-dialog"
    width="673px"
  >
    <a-form ref="ruleFormRef" :model="state.ruleForm" layout="vertical">
      <div class="date-select-drawer">
        <a-radio-group
          type="button"
          v-model="state.ruleForm.rangeType"
          class="date-type"
          @change="rangeTypeChange"
        >
          <a-radio value="RELATIVE">相对时间</a-radio>
          <a-radio value="FIXED">固定时间</a-radio>
        </a-radio-group>
        <div
          class="date-compontent"
          :style="{
            height: state.ruleForm.rangeType == 'FIXED' ? '380px' : '419px'
          }"
        >
          <div class="left">
            <a-form-item
              label="开始时间"
              field="startDate"
              :validate-trigger="['change']"
              :rules="state.rules.startDate"
            >
              <DateSelect
                placeholder="开始日期"
                v-model="state.ruleForm.startDate"
                :rangeType="state.ruleForm.rangeType"
                :tagData="props.tagData"
              ></DateSelect>
            </a-form-item>
          </div>
          <div class="right">
            <a-form-item
              label="结束时间"
              field="endDate"
              :validate-trigger="['change']"
              :rules="state.rules.endDate"
            >
              <DateSelect
                placeholder="结束日期"
                v-model="state.ruleForm.endDate"
                :rangeType="state.ruleForm.rangeType"
                :tagData="props.tagData"
              ></DateSelect>
            </a-form-item>
          </div>
        </div>
      </div>
      <div
        class="fast"
        v-if="state.ruleForm.rangeType == 'FIXED' && props.tagData.id != -4"
      >
        <div class="label">快捷方式：</div>
        <a-button
          type="text"
          v-if="props.tagData.id == -3"
          @click="getFastDate(1)"
          >昨天</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -3" />
        <a-button
          type="text"
          v-if="props.tagData.id == -3"
          @click="getFastDate(2)"
          >今天</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -3" />
        <a-button
          type="text"
          v-if="props.tagData.id == -3"
          @click="getFastDate(3)"
          >最近3天</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -3" />
        <a-button
          type="text"
          v-if="props.tagData.id == -3"
          @click="getFastDate(4)"
          >最近7天</a-button
        >

        <a-button
          type="text"
          v-if="props.tagData.id == -5"
          @click="getFastDate(5)"
          >上周</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -5" />
        <a-button
          type="text"
          v-if="props.tagData.id == -5"
          @click="getFastDate(6)"
          >本周</a-button
        >

        <a-button
          type="text"
          v-if="props.tagData.id == -2"
          @click="getFastDate(7)"
          >上月</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -2" />
        <a-button
          type="text"
          v-if="props.tagData.id == -2"
          @click="getFastDate(8)"
          >本月</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -2" />
        <a-button
          type="text"
          v-if="props.tagData.id == -2"
          @click="getFastDate(9)"
          >近3月</a-button
        >

        <a-button
          type="text"
          v-if="props.tagData.id == -1"
          @click="getFastDate(10)"
          >去年</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -1" />
        <a-button
          type="text"
          v-if="props.tagData.id == -1"
          @click="getFastDate(11)"
          >本年</a-button
        >
        <a-divider direction="vertical" v-if="props.tagData.id == -1" />
        <a-button
          type="text"
          v-if="props.tagData.id == -1"
          @click="getFastDate(12)"
          >近3年</a-button
        >
      </div>
    </a-form>
  </a-modal>
</template>
<style lang="scss" scoped>
@import './index.scss';
</style>